package me.trytofeel.controller;

import me.trytofeel.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@Controller
@ResponseBody
@RequestMapping(produces = "application/json;charset=utf-8")
public class TestController {

    // 获取基本类型
    @RequestMapping("string") // .../string
    public String  getString(String username, int id) {
        System.out.println("username = " + username);
        System.out.println("id = " + id);
        return "你给我传了" + username + "和" + id;
    }

    // 获得实体类型
    @RequestMapping("toUser")
    public String getString(User user) { // 浏览器直接传递对象的属性，方法形参写对象类型，就会自动创建这个对象
        System.out.println("user = " + user); // 请求的乱码，要去配tomcat插件
        return user.getUsername() + user.getUserId();
    }

    // 获得数组类型
    @RequestMapping("array") // array?hobby=aaa&hobby=bb&hobby=cc
    public String getArray(String[] hobby) {
        List<String> strings = Arrays.asList(hobby);
        return strings.toString();
    }

    // 获得集合类型
    @RequestMapping("list") // list?hobby=aaa&hobby=bb&hobby=cc
    public String getList(@RequestParam List<String> hobby) {
        return hobby.toString();
    }

    @RequestMapping("test1")
    public String test1(@RequestParam(value = "user", required = false, defaultValue = "六六") String username) { // 取别名 required = false (非必填) defaultValue = "六六" (默认值) | ?user=王维 ≠ ?username=王维
        return username;
    }

    // 从js发送的json中获取
    @RequestMapping("getUser")
    public User getUser(@RequestBody User user) { // 如果 要以 Json格式来接收参数，就需要一个注解
        return user;
    }

    // 获取json数组
    @RequestMapping("getUserList")
    public List<User> getUserList(@RequestBody List<User> userList) {
        return userList;
    }

}
